import React from 'react';
import { connect } from 'umi';
import { Form, Input, Radio, DatePicker, Button, Divider, message } from 'antd';
import moment from 'moment';
import { useRequest, useCollapse, defaultFormatResult, useWorkFlow } from '@/hooks';
import FileUpload from '@/components/Custom/FileUpload';
import { BottomAction } from '@/components';
import pageTabUtil from '@/utils/pageTabUtil';
import { PageContainer, Collapse } from '@/molecules';
// import { PersonalCard, DiscussArrange } from './containers';
import { PersonalCard } from './containers';
import { addFeedback, getInformalEmployeeInfo } from './services';
import styles from './index.less';

const { Panel } = Collapse;

const Feedback = ({ form, location, user }) => {
    const { query } = location;
    const { getFieldDecorator, getFieldValue } = form;

    const { activeKey, onChange, openAll } = useCollapse(['1', '2'], []);

    const { data: employeeInfo, loading: infoLoading } = useRequest(
        () => getInformalEmployeeInfo(query?.employeeCode),
        {
            refreshDeps: [query?.employeeCode],
            ready: !!query?.employeeCode,
            ...defaultFormatResult
        }
    );

    const { loading, run } = useRequest(addFeedback, {
        manual: true,
        onSuccess: res => {
            if (res) {
                const { code, msg } = res;
                if (code === 10000) {
                    message.success('操作成功');
                    pageTabUtil.goBack();
                } else {
                    message.error(msg);
                }
            }
        }
    });

    const { launch } = useWorkFlow({ launchParam: { type: 'DimissionProxyApply' } });

    const handleSubmit = () => {
        form.validateFieldsAndScroll({ scroll: { alignWithTop: true } }, async (err, values) => {
            if (!err) {
                const {
                    opinion,
                    feedbackTime,
                    content,
                    resourceRelation
                    // interviewDate,
                    // interviewStartTime,
                    // interviewEndTime,
                    // schedule,
                    // ...rest
                } = values;
                // let arrange = null;
                // if ([1, 3].includes(opinion)) {
                //     arrange = {
                //         ...rest,
                //         interviewType: 1,
                //         interviewStartTime: `${interviewDate.format('YYYY-MM-DD')} ${interviewStartTime.format(
                //             'HH:mm:00'
                //         )}`,
                //         interviewEndTime: `${interviewDate.format('YYYY-MM-DD')} ${interviewEndTime.format('HH:mm:00')}`
                //     };
                // }

                const params = {
                    regularProbationId: query?.id,
                    employeeCode: query?.employeeCode,
                    probationFeedbackDTO: {
                        opinion,
                        content,
                        feedbackTime: feedbackTime ? feedbackTime.format('YYYY-MM-DD HH:mm:ss') : '',
                        resourceRelation: resourceRelation?.uploadResourceFile
                            ? [resourceRelation?.uploadResourceFile]
                            : []
                    }
                };
                // if (arrange) {
                //     params.probationInterviewArrangeDTO = arrange;
                // }
                console.log(params);
                run(params);

                // 终止试用，自动离职？？？
                if (opinion === 3) {
                    launch({ leaverEmployeeCode: query?.employeeCode });
                }
            } else {
                openAll();
                setTimeout(() => {
                    form.validateFieldsAndScroll({ scroll: { alignWithTop: true } });
                });
            }
        });
    };

    return (
        <PageContainer loading={infoLoading}>
            <BottomAction>
                <Button onClick={() => pageTabUtil.goBack()} disabled={loading}>
                    取消
                </Button>
                <Button type="primary" onClick={handleSubmit} loading={loading}>
                    确定
                </Button>
            </BottomAction>
            <PersonalCard data={employeeInfo} />
            <Divider style={{ margin: '24px 0 0' }} />
            <Collapse bordered={false} style={{ marginBottom: 16 }} activeKey={activeKey} onChange={onChange}>
                <Panel header="反馈内容" key="1">
                    <Form className={styles.formWrap}>
                        <div style={{ display: 'flex' }}>
                            <Form.Item label="反馈人" style={{ width: '50%' }}>
                                {user?.employeeName || ''}
                            </Form.Item>
                            <Form.Item label="反馈时间" style={{ width: '50%', marginLeft: 30 }}>
                                {getFieldDecorator('feedbackTime', {
                                    initialValue: moment(),
                                    rules: [
                                        {
                                            required: true,
                                            message: '反馈时间不能为空'
                                        }
                                    ]
                                })(
                                    <DatePicker
                                        showTime={{ format: 'HH:mm' }}
                                        format="YYYY-MM-DD HH:mm"
                                        placeholder="请选择反馈时间"
                                        style={{ width: '100%' }}
                                    />
                                )}
                            </Form.Item>
                        </div>
                        <Form.Item label="反馈意见">
                            {getFieldDecorator('opinion', {
                                initialValue: undefined,
                                rules: [
                                    {
                                        required: true,
                                        message: '反馈意见不能为空'
                                    }
                                ]
                            })(
                                <Radio.Group>
                                    <Radio value={1}>申请提前转正</Radio>
                                    <Radio value={2}>继续试用</Radio>
                                    <Radio value={3}>终止试用</Radio>
                                </Radio.Group>
                            )}
                        </Form.Item>
                        <Form.Item label="内容">
                            {getFieldDecorator('content', {
                                initialValue: '',
                                rules: [
                                    {
                                        required: true,
                                        message: '内容不能为空'
                                    }
                                ]
                            })(
                                <Input.TextArea
                                    placeholder="请输入内容"
                                    autoSize={{ minRows: 3, maxRows: 6 }}
                                    maxLength={500}
                                />
                            )}
                        </Form.Item>
                        <Form.Item label="相关资料">
                            {getFieldDecorator('resourceRelation')(
                                <FileUpload
                                    checkFileSizeMsg="文件大小不能超过10MB！"
                                    checkFileSize={10}
                                    categoryCode="probationFeedbackFile"
                                    businessCode="ProbationFeedback"
                                    checkFileType="pdf、doc、docx、jpg、jpeg、png、rar、xls、xlsx"
                                    checkFileTypeMsg="只能上传 pdf、doc(x)、xls(x)、jp(e)g、png、rar 格式的文件！"
                                >
                                    <Button
                                        style={{ marginTop: 4 }}
                                        icon="upload"
                                        disabled={getFieldValue('resourceRelation')?.allFileList?.length > 4}
                                    >
                                        上传文件
                                    </Button>
                                    <div
                                        style={{ marginTop: 4, color: 'rgba(0,0,0,.25)' }}
                                        onClick={e => e.stopPropagation()}
                                    >
                                        支持 pdf、doc、docx、jpg、jpeg、png、rar、xls、xlsx
                                        等格式的附件，单个文件大小为10MB以内
                                    </div>
                                </FileUpload>
                            )}
                        </Form.Item>
                    </Form>
                </Panel>
                {/* {[1, 3].includes(getFieldValue('opinion')) && (
                    <Panel header="反馈面谈安排" key="2">
                        <DiscussArrange form={form} interviewType={1} />
                    </Panel>
                )} */}
            </Collapse>
        </PageContainer>
    );
};

export default connect(({ user }) => ({ user: user.currentUser }))(Form.create()(Feedback));
